<?php

if (!defined('CORE_PATH'))
    die('Access Denied');

// EventManager class definition
class EventsModule extends Module {

    protected $models = array('Event', 'EventCategory');
    protected $template = "events.php";

    public function __construct() {
        parent::__construct(dirname(__FILE__));
    }

    public function index() {
        $categories = $this->EventCategory->find(array(
            'filter' => array('SiteID' => SITE_ID)
        ));

        $this->set('categories', $categories);
    }

    public function list_events() {

        $this->autoLayout = false;

        // get the number of records to be returned and the position to start returning
        // them from limit for the number of records to returned
        $limit = isset($_POST['limit']) ? $_POST['limit'] : 20;
        $start = isset($_POST['start']) ? $_POST['start'] * $limit : 0;

        // get the category to which the articles belong
        $cat = $_POST['category'];

        // get a category object
        $category = $this->getEventCategory($cat);

        // retrieve the articles in the specified category
        $events = $category->getEvents($start, $limit, false, false);

        // get the total number of articles in this category
        $total_articles = $category->getTotalEventCount();

        $this->set(compact('events', 'total_articles', 'start'));
    }

    public function add() {

        if (isset($_POST['EventCategory'])) {
            $this->autoRender = false;

            $event = new Event(array(
                'EventCategory' => $_POST['EventCategory'],
                'EventName' => $_POST['EventName'],
                'EventDesc' => $_POST['EventDesc'],
                'Time' => $_POST['Time'],
                'EventDuration' => $_POST['EventDuration'],
                'Date' => $_POST['EventDuration'] == "single" ? $_POST['Date'] : $_POST['StartDate'],
                'StartDate' => $_POST['EventDuration'] == "single" ? $_POST['Date'] : $_POST['StartDate'],
                'EndDate' => $_POST['EndDate'],
                'Venue' => $_POST['Venue'],
                'FriendlyURL' => $_POST['FriendlyURL']
            ));

            $event->save();

            $this->redirect(array('action' => 'index'));
        }

        $categories = $this->EventCategory->find(array(
            'filter' => array('SiteID' => SITE_ID)
        ));

        $this->set('categories', $categories);
    }

    public function edit($id) {

        if (isset($_POST['EventCategory'])) {
            $this->autoRender = false;

            $event = new Event(array(
                'EventCategory' => $_POST['EventCategory'],
                'EventName' => $_POST['EventName'],
                'EventDesc' => $_POST['EventDesc'],
                'Time' => $_POST['Time'],
                'EventDuration' => $_POST['EventDuration'],
                'Date' => $_POST['EventDuration'] == "single" ? $_POST['Date'] : $_POST['StartDate'],
                'StartDate' => $_POST['EventDuration'] == "single" ? $_POST['Date'] : $_POST['StartDate'],
                'EndDate' => $_POST['EndDate'],
                'Venue' => $_POST['Venue'],
                'FriendlyURL' => $_POST['FriendlyURL'],
                'id' => $_POST['id']
            ));

            $event->save();

            $this->redirect(array('action' => 'index'));
        }

        $event = $this->Event->findFirst(array(
            'filter' => array('id' => $id)
        ));

        $categories = $this->EventCategory->find(array(
            'filter' => array('SiteID' => SITE_ID))
        );

        $this->set('event', $event);
        $this->set('categories', $categories);
    }

    public function deleteEvents() {
        $this->autoRender = false;

        if ($this->Request->isAjax() && isset($_POST['event_ids'])) {
            $this->Event->delete(array(
                'filter' => array('id IN' => explode(",", $_POST['event_ids']))
            ));

            return;
        }
    }

    public function publishEvent() {
        $this->autoRender = false;

        if ($this->Request->isAjax()) {
            $event = new Event(array(
                'id' => $_POST['id'],
                'published' => $_POST['action'] == "publish" ? "true" : "false"
            ));
            $event->save();
        }
    }

    public function addCategory() {
        $this->autoRender = false;

        if ($this->Request->isAjax() && isset($_POST['CategoryName'])) {
            $category = new EventCategory(array(
                'CategoryName' => $_POST['CategoryName'],
                'CategoryAlias' => String::slug($_POST['CategoryName']),
                'CategoryDescription' => $_POST['CategoryDescription']
            ));
            $category->save();

            echo $category->toJSON();
        }
    }

    public function deleteCategory() {
        $this->autoRender = false;

        if ($this->Request->isAjax() && isset($_POST['event_ids'])) {
            $this->EventCategory->delete(array(
                'filter' => array('id IN' => explode(",", $_POST['category_id']))
            ));

            return;
        }
    }

    public function getEventCategory($category_id) {

        return $this->EventCategory->findFirst(array(
                    'filter' => array(
                        'SiteID' => SITE_ID,
                        'OR' => array(
                            'id' => $category_id,
                            'CategoryAlias' => $category_id
                        )
                    )
        ));
    }

    /**
     * Returns a list of events from the database
     * @return array the events 
     */
    public function getEvents($start = 0, $limit = NULL, $publishedOnly = true, $excludePast = true) {
        $db = $this->getDatabase();
        $pub = $publishedOnly ? " AND Published = 'true' " : "";
        $past = $excludePast ? " AND (StartDate >= CURRENT_DATE OR EndDate >= CURRENT_DATE) " : "";

        $query = sprintf("SELECT Event.* FROM {$this->Event->getTableName()} AS Event
							INNER JOIN {$this->EventCategory->getTableName()} ec ON ec.id = Event.EventCategory 
							WHERE ec.SiteID = %s {$pub} {$past} ORDER BY StartDate ASC ", $db->sanitizeInput(SITE_ID, 'int'));

        if ($limit != NULL) {
            $query = sprintf("%s LIMIT %s, %s", $query, $db->sanitizeInput($start, 'int'), $db->sanitizeInput($limit, 'int'));
        }

        $db->query($query, true);
        $events = array();

        for ($i = 0; $i < $db->getResultCount(); $i++) {
            array_push($events, new Event($db->getRow($i)));
        }

        return $events;
    }

    /**
     *
     * @param mixed $id the id or alias to use to find the event
     * @return Event an Event object
     */
    public function getEvent($id) {
        $db = $this->getDatabase();

        $query = sprintf("SELECT Event.* FROM {$this->Event->getTableName()} AS Event "
                . "INNER JOIN {$this->EventCategory->getTableName()} ec ON ec.id = Event.EventCategory "
                . "WHERE ec.SiteID = %s AND Event.id = %s OR FriendlyURL = %s AND Published = 'true' ", $db->sanitizeInput(SITE_ID, 'int'), $db->sanitizeInput($id, 'int'), $db->sanitizeInput($id, 'text'));

        $db->query($query, true);
        $event = new Event($db->getRow());

        return $event;
    }

    public function getFeedURL() {
        if (SEF_URLS) {
            return kan_fix_url("../" . SITE_TAG . "/feed/events/");
        }

        return kan_fix_url("../pages/feed.php?siteid=" . SITE_TAG . "&content=events");
    }

    public function render() {
        global $site;

        $event = NULL;
        $category = NULL;

        if (isset($_GET['category'])) {
            $category = $this->getEventCategory(kan_get_parameter('category'));
        }

        if (isset($_GET['id'])) {
            $event = $this->getEvent(kan_get_parameter('id'));
            $site->setData('SiteDescription', substr(strip_tags($event->getDescription()), 0, 200));
        } else if (isset($_GET['url'])) {
            // the url parameters
            $parts = explode("/", kan_get_parameter('url'));

            // if the url parameters contains more than two parameters then the url is
            // valid and the article can be loaded. e.g. news/article-title
            if (count($parts) >= 1 && !empty($parts[0])) {
                $category = $this->getEventCategory(kan_clean_input($parts[0]));
            }

            if (count($parts) >= 2 && !empty($parts[1])) {
                $event = $this->getEvent(kan_clean_input($parts[1]));
                $site->setData('SiteDescription', substr(strip_tags($event->getDescription()), 0, 200));
            }
        }

        $this->set('event', $event);
        $this->set('category', $category);

        // call parent render function
        parent::render();
    }

}

?>